<template>
  <div class="add-user">
    <el-dialog :title="title" :visible.sync="visible" width="800px" @close="formCancel()">
      <el-form ref="editForm" :model="formData" :inline="true" :rules="rules" label-position="right" label-width="80px">
        <div class="title">
          <span />
          <span>基本信息</span>
          <span />
        </div>
        <el-row>
          <el-col :span="11">
            <el-form-item label="账号" prop="account">
              <el-input v-model.trim="formData.account" type="text" placeholder="请输入账号" autocomplete="off" clearable :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" type="text" placeholder="请输入姓名" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!editFlag">
          <el-col :span="11">
            <el-form-item label="密码" prop="password">
              <el-input v-model.trim="formData.password" type="password" placeholder="请输入密码" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="重复密码" prop="confirm">
              <el-input v-model.trim="formData.confirm" type="password" placeholder="请输入确认密码" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="昵称">
              <el-input v-model="formData.nickName" type="text" placeholder="请输入昵称" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="生日">
              <el-date-picker
                v-model="formData.birthday"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择生日"
                :picker-options="pickerOptions"
                style="width:90%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio :label="1" size="large">男</el-radio>
                <el-radio :label="2" size="large">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" type="text" placeholder="请输入邮箱" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" type="text" placeholder="请输入手机号" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="电话">
              <el-input v-model="formData.tel" type="text" placeholder="请输入电话" autocomplete="off" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          <span />
          <span>员工信息</span>
          <span />
        </div>
        <el-row>
          <el-col :span="11">
            <el-form-item label="部门" prop="empInfoReq.orgName">
              <el-select v-model="formData.empInfoReq.orgName" placeholder="请选择" :popper-append-to-body="false" @change="$forceUpdate()">
                <el-option :value="selectTree" class="set-style">
                  <el-tree ref="tree" default-expand-all :data="dataTree" :props="defaultProps" :highlight-current="true" @node-click="node" />
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="11">
            <el-form-item label="工号">
              <el-input v-model="formData.empInfoReq.jobNum" type="text" placeholder="请输入工号" autocomplete="off" clearable @input="inputJob" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="11">
            <el-form-item label="职位信息" prop="empInfoReq.posIdList">
              <el-select v-model="formData.empInfoReq.posIdList" multiple @change="$forceUpdate()">
                <el-option
                  v-for="(item,indx) in posArr"
                  :key="indx+'ind'"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item />
          </el-col>
        </el-row> -->
        <el-form-item style="margin-top:20px;width: 100%;display: flex;justify-content: center;">
          <el-button style="margin-right:20px;" @click="formCancel()">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </el-form-item>
        <!-- </el-form> -->
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { SetUser, GetDepTree, UserGetList, GetPosList, AccountVerify } from '@/api/system';
const form = {
  account: '',
  adminType: 0,
  birthday: '',
  email: '',
  id: '',
  name: '',
  nickName: '',
  phone: '',
  sex: '',
  status: 0,
  tel: '',
  empInfoReq: {
    extIds: [
      {}
    ],
    posIdList: [],
    orgId: '',
    orgName: '',
    jobNum: ''
  }
};
export default {
  name: 'AddUser',
  components: {},
  props: {},
  data() {
    const validConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码！'))
      } else if (value !== this.formData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validVerify = (rule, value, callback) => {
      console.log('value', value)
      if (!this.disabled) {
        AccountVerify({ account: value }).then(res => {
          console.log('res====', res)
          res.success && callback()
          !res.success && callback(new Error('账号已存在，请重新输入账号'))
        })
      } else {
        callback()
      }
    }
    return {
      formData: {
        account: '',
        adminType: 0,
        birthday: '',
        email: '',
        id: '',
        name: '',
        nickName: '',
        phone: '',
        sex: '',
        status: 0,
        tel: '',
        empInfoReq: {
          extIds: [
            {}
          ],
          posIdList: [],
          orgId: '',
          orgName: '',
          jobNum: ''
        }
      },
      visible: false,
      infoShow: true,
      rules: {
        account: [
          {
            required: true, message: '请输入账号', trigger: 'blur'
          },
          {
            min: 5, message: '账号不能少于5个字符！', trigger: 'blur'
          },
          {
            validator: validVerify, trigger: 'blur'
          }
        ],
        name: [
          {
            required: true, message: '请输入姓名！', trigger: 'blur'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码！', trigger: 'blur'
          },
          {
            pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])([0-9A-Za-z_\W]){6,12}$/, message: '密码必须包含数字和字母，可包含特殊字符，长度为6-12位！', trigger: 'blur'
          }
        ],
        confirm: [
          {
            required: true, message: '请输入确认密码！', trigger: 'blur'
          },
          {
            validator: validConfirm, trigger: 'blur'
          }
        ],
        sex: [
          {
            required: true, message: '请选择性别！', trigger: 'blur'
          }
        ],
        email: [
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确格式的邮箱！', trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true, message: '请输入手机号', trigger: 'blur'
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确格式的手机号！', trigger: 'blur'
          }
        ],
        empInfoReq: {
          orgName: [
            {
              required: true, message: '请选择部门', trigger: 'blur'
            }
          ],
          posIdList: [
            {
              required: true, message: '请选择职位信息', trigger: 'blur'
            }
          ]
        }
      },
      selectTree: [
        {
          title: '',
          id: ''
        }
      ],
      dataTree: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      disabled: false,
      posArr: [],
      posIdArr: [],
      attachData: [],
      title: '新增用户',
      editFlag: false,
      newArr: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      empInfoRes: {
        extOrgPos: [],
        jobNum: '',
        orgId: '',
        orgName: '',
        positions: []
      }
    };
  },
  created() {
    this.getTreeData()
    this.getPos()
  },
  mounted() {},
  methods: {
    getTreeData() {
      GetDepTree().then(res => {
        if (res.code === 200) {
          this.dataTree = res.data
        }
      })
    },
    getPos() {
      GetPosList().then(res => {
        if (res.code === 200) {
          const posArr = res.data;
          const newArr = []
          posArr.forEach(v => {
            newArr.push({
              posCode: v.code,
              posId: v.id,
              posName: v.name
            })
          })
          this.posArr = posArr
          this.posIdArr = newArr
          console.log('hhhhh', this.posIdArr)
        }
      })
    },
    add() {
      this.formData = Object.assign({}, form)
      this.formData.empInfoReq = {
        extOrgPos: [],
        posIdList: [],
        orgId: '',
        orgName: '',
        jobNum: ''
      };
      this.editFlag = false
      this.title = '新增用户'
      this.visible = true
      this.disabled = false
      this.$refs['editForm'] && this.$refs['editForm'].clearValidate();
    },
    edit(row) {
      UserGetList({ id: row.id }).then(res => {
        const { data } = res
        const newArr = []
        if (data.empInfoRes.positions) {
          data.empInfoRes.positions.forEach(v => {
            newArr.push(v.posId.toString())
          })
        }
        this.formData.empInfoReq = Object.assign(this.empInfoRes, data.empInfoRes)
        this.formData.empInfoReq.posIdList = newArr
        delete this.formData.empInfoReq.positions
        this.editFlag = true
        this.formData = Object.assign(this.formData, data)
        this.title = '编辑用户'
        setTimeout(() => {
          this.visible = true
          this.disabled = true
          this.$refs['editForm'].clearValidate();
        }, 300)
      })
    },
    node(e) {
      this.$nextTick(() => {
        this.formData.empInfoReq.orgName = e.title
        this.formData.empInfoReq.orgId = e.id
        this.$forceUpdate();
      })
    },
    changePos(e) {
      this.$forceUpdate()
    },
    inputJob() {
      this.$forceUpdate();
    },
    formCancel() {
      this.visible = false
    },
    submit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          SetUser(this.formData).then(res => {
            res.success && this.$message({
              message: this.title.substring(0, 2) + '成功',
              type: 'success'
            })
            this.visible = false
            this.$emit('reload')
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-user{
  ::v-deep .el-dialog__body{
    padding-top: 0px;
  }
  ::v-deep .el-form-item{
    margin-bottom: 35px;
  }
  .title{
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    display: flex;
    align-items: center;
    span:first-child{
      display: inline-block;
      width: 60px;
      height: 1px;
      border-top: 1px solid #e8e8e8;
    }
    span:nth-child(2) {
      display: inline-block;
      width: 100px;
      text-align: center;
    }
    span:last-child {
      display: inline-block;
      flex: 1;
      height: 1px;
      border-top: 1px solid #e8e8e8;
    }
  }
  ::v-deep .el-tree-node__content{
    height: 40px;
  }

  .info-attach{
    ::v-deep .el-form-item__content{
      width: 80%;
    }
  }
  .add-line{
    width: 90%;
    height: 30px;
    margin: 20px auto;
    border: 1px dashed #DCDFE6;
    display: flex;
    justify-content: center;
    align-items: center;
    span{
      display: block;
    }
  }
  .set-style {
    min-height: 200px;
    padding: 0 !important;
    margin: 0;
    overflow: auto;
    cursor: default !important;
  }
}
</style>
